package com.mycinema.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.UploadContext;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.mycinema.biz.CategoryBiz;
import com.mycinema.biz.MovieBiz;
import com.mycinema.entity.Category;
import com.mycinema.entity.Movie;

@Controller
@RequestMapping("/admin")
public class MovieController {
	@Autowired
	private MovieBiz movieBiz;
	@Autowired
	private CategoryBiz categoryBiz;

	@RequestMapping("/edits")
	public String edit(
			@RequestParam(required = false, defaultValue = "0") int id,
			Model model) {
		if (id > 0) {
			Movie movie = movieBiz.fetchById(id);
			model.addAttribute("movie", movie);
		}
		List<Category> categories = categoryBiz.getAll();
		model.addAttribute("categories", categories);
		return "movie-edit";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(
			Movie movie,
			@RequestParam(name = "movieImage", required = false) MultipartFile movieImage,
			HttpServletRequest request) {
		if (movie.getId() > 0) {
			movieBiz.update(movie);
		} else {
			movieBiz.add(movie);
		}
		if (!movieImage.isEmpty()) { // 检查文件是否为空，空表示未上传，非空则保存文件
			// 获得converImages的物理路径
			String path = request.getSession().getServletContext()
					.getRealPath("MovieImages");
			String filename = path + "/" + movie.getMovieCode() + ".jpg";
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(filename);
				// 将用户上传文件写入目标文件
				fos.write(movieImage.getBytes());
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return "redirect:list?id=" + movie.getId();
	}

	// 日期格式绑定,解决java.util.Date格式问题
	// @InitBinder //数据绑定到方法的参数之前执行
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setLenient(false);// 不单控制格式，还要控制日期是否合法
		// 注册自定义的日期格式
		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(
				sdf, false));
	}

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String Upload() {
		return "upLood";
	}

	@RequestMapping(value = "/upLoad", method = RequestMethod.POST)
	public String upLoad(
			@RequestParam(name = "attachs", required = false) MultipartFile[] attachs,
			HttpServletRequest request) {
		// 获取MovieImages的物理目录
		String path = request.getServletContext().getRealPath("MovieImages");
		for (MultipartFile multipartFile : attachs) {
			// 获得原始文件名
			if (!multipartFile.isEmpty()) {
				String oldName = multipartFile.getOriginalFilename();
				// 获取文件扩展名
				String extension = FilenameUtils.getExtension(oldName);
				// 生成新的文件名
				String fileName = path + File.separator
						+ System.currentTimeMillis() + "." + extension;
				// 构建文件
				File file = new File(fileName);
				// 将上传文件写入目标文件
				try {
					multipartFile.transferTo(file);
					System.out.println("上传成功");
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return "redirect:/list";
	}

	// 文件下载
	@RequestMapping(value = "/downLoad")
	public void downLoad(String fileName, HttpServletResponse response,
			HttpServletRequest request) {
		//设置响应头的信息
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		//告诉浏览器以附件的形式打开文件
		response.setHeader("content-disposition", "attachement;filename="+ fileName);
		try {
			// 获取文件的物理路径
			String path = request.getSession().getServletContext().getRealPath("MovieImages")+File.separator+fileName;
			File file = new File(path);
			FileInputStream inputStream = new FileInputStream(file);
			//获取客户端的二进制输出流
			OutputStream os = response.getOutputStream();
			byte[] bt = new byte[1024];
			while (( inputStream.read(bt)) != -1) {
				//将字节数组的内容写入二进制输出流
				os.write(bt);
			}
			inputStream.close();
			os.close();
			System.out.println("下载完成");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
